package ywpt.web.action.system;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.util.WebUtils;
import ywpt.components.acegi.domain.Role;
import ywpt.core.exception.UniqueConstraintException;
import ywpt.core.web.BaseAction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ecside.util.ServletUtils;

import ywpt.service.system.RoleService;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class RoleAction extends BaseAction implements ModelDriven<Role>, Preparable {
	private static final long	serialVersionUID	= 2353017174050977234L;
	protected final Log			log					= LogFactory.getLog(RoleAction.class);
	private List<Role>			roleList			= new ArrayList<Role>();
	private RoleService			roleService;
	private Long				id;
	private Long				resId;
	private Role				role;
	private List<Long>			selectedResources	= new ArrayList<Long>();
	protected static int		DEFAULT_PAGE_SIZE	= 20;

	public RoleAction() {
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public List<Role> getRoleList() {
		return roleList;
	}

	public void setRoleList(List<Role> roleList) {
		this.roleList = roleList;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long getResId() {
		return resId;
	}

	public void setResId(Long resId) {
		this.resId = resId;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}
	
	public List<Long> getSelectedResources() {
		return selectedResources;
	}

	public void setSelectedResources(List<Long> selectedResources) {
		this.selectedResources = selectedResources;
	}

	@Override
	@SuppressWarnings("unchecked")
	public String execute() {
		role = new Role();
		return list();
	}

	/**
	 * 新增角色
	 * 
	 * @return
	 */
	public String input() {
		return INPUT;
	}
	
	public String addResources() {
		return INPUT;
	}

	/**
	 * 编辑角色
	 * 
	 * @return
	 */
	public String edit() {
		this.role = roleService.getRoleById(new Long(getId()));
		return INPUT;
	}
	
	/**
	 * 查看角色
	 * @return
	 */
	public String view() {
		return SUCCESS;
	}

	public String save() {
		try {
			if (id == null) {
				roleService.saveRole(role);
			} else {
				roleService.updateRole(role);
			}
			this.addActionMessage("角色信息已保存!");
			//return "view";
		} catch (UniqueConstraintException e) {
			if (e.getMessage().indexOf("名称") != -1) {
				this.addFieldError("roleName", "名称重复");
			} else {
				this.addActionError("保存错误:" + e.getMessage());
			}
			//return INPUT;
		}
		return INPUT;
	}

	public String saveResources() {
		if (selectedResources != null && selectedResources.size() > 0) {
			roleService.addResources(role, selectedResources);
		} else {
			this.addActionMessage("请选择要分配的权限!");
			return INPUT;
		}
		return SUCCESS;
	}

	/**
	 * 角色列表
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String list() {
		roleList.addAll(roleService.getAllRoles());
		return SUCCESS;
	}

	/**
	 * 删除角色信息
	 * @return
	 */
	public String delete() throws Exception {
		if (id != null) {
			Role role=roleService.getRoleById(id);
			if(null!=role && role.getOperations().isEmpty())
			{
				roleService.removeRole(id);
				return SUCCESS;
			}
			else 
			{
				this.addActionMessage("该角色已经参与授权，请先取消授权再删除！");
				return INPUT;
			}
		}
		else
		{
			this.addActionMessage("请选择要删除的角色！");
			return INPUT; 
		}
	}
	
	
	/**
	 * 删除(Ajax方式) 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String deleteAjax() throws Exception {
		List<Map<String, String>> list = ServletUtils.getParameterMaps(getRequest());
		Long roleIds[] = new Long[list.size()];
		int results[] = null;
		for (int i = 0; i < list.size(); i++) {
			Map<String, String> roleMap = list.get(i);
			roleIds[i] = Long.valueOf(roleMap.get("recordKey"));
		}
		results = roleService.removeRoles(roleIds);
		ServletUtils.defaultAjaxResopnse(list, results, getRequest(), getResponse());
		return NONE;
	}
	
	@SuppressWarnings("unchecked")
	public String deleteResAjax() throws Exception {
		List<Map<String, String>> list = ServletUtils.getParameterMaps(getRequest());
		Long resIds[] = new Long[list.size()];
		int results[] = null;
		for (int i = 0; i < list.size(); i++) {
			Map<String, String> resMap = list.get(i);
			resIds[i] = Long.valueOf(resMap.get("recordKey"));
		}
		results = roleService.removeResources(role,resIds);
		ServletUtils.defaultAjaxResopnse(list, results, getRequest(), getResponse());
		return NONE;
	}

	@SuppressWarnings("unchecked")
	public String roleTree() throws Exception {
		JSONArray jsonArray = null;
		HttpServletResponse response = this.getResponse();
		response.setHeader("Content-Type", "text/html; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			List<Map<String, Object>> children = roleService.getRoleTree();
			jsonArray = JSONArray.fromObject(children);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		out.write(WebUtils.toString(jsonArray));
		return NONE;
	}


	/**
	 * 选择所有角色
	 * @return
	 */
	public String select() {
		setRoleList(roleService.getAllRoles());
		return SUCCESS;
	}
	

	public Role getModel() {
		return role;
	}

	
	public void prepare() throws Exception {
		if (id != null) {
			this.role = roleService.getRoleById(new Long(getId()));
		} else {
			this.role = new Role();
		}
	}
}